package com.hui.ruiji.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hui.ruiji.common.BaseContext;
import com.hui.ruiji.common.R;
import com.hui.ruiji.entity.User;
import com.hui.ruiji.service.UserService;
import com.hui.ruiji.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 移动端发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMessage(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();

        if (!StringUtils.isEmpty(phone)) {
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送短息（不做这步了）
            log.info("验证码是:{}", code);
            //将生成的验证码保存到session中
            session.setAttribute("phone", code);

            return R.success("验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动端用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpSession session) {
        //从map里获取手机号和验证码
        String phone = user.get("phone").toString();
        String code = user.get("code").toString();

        //从session中获取保存的验证码
        Object codeInSession = session.getAttribute("phone");

        //进行验证码的验证
        if (codeInSession != null && code.equals(codeInSession)) {
            //比对成功，登陆成功

            //判断当前手机号是否是新用户，如果是新用户，自动注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User userOne = userService.getOne(queryWrapper);
            if (userOne == null) {
                userOne = new User();
                userOne.setPhone(phone);
                userOne.setStatus(1);
                userService.save(userOne);
            }
            session.setAttribute("user", userOne.getId());
            return R.success(userOne);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        BaseContext.setCurrentId(null);
        return R.success("退出成功");
    }
}
